/**
 * Created by yijx on 2017/3/13.
 */
//当前选中任务
var selectedTask = new Array();
//当前编辑的备料申请
var editReqpickm =new Array();


//表头宽度适应表体
function adaptTH() {
    $("table").children("thead").find("td,th").each(function () {
        var idx = $(this).index();
        var td = $(this).closest("table").children("tbody")
            .children("tr:first").children("td,th").eq(idx);
        $(this).width(td.width());
    })
};

//遮罩处理
function  mask() {
    jQuery(document).ready(function($) {
        $('.theme-login').click(function(){
            $('.theme-popover-mask').fadeIn(100);
            $('.theme-popover').slideDown(200);
        })
        $('.theme-poptit .close').click(function(){
            $('.theme-popover-mask').fadeOut(100);
            $('.theme-popover').slideUp(200);
        })
    })
}

$(function () {
    taskQuery();
    mask();
    adaptTH();

    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        e.target; // 激活的标签页
        e.relatedTarget; // 前一个激活的标签页
        adaptTH();
    })

    var querytask=$("#reqmattab"),
        achievetask=$("#donetasktab"),
        reqpickm = $('#reqpickm');


    //查询生产任务
    querytask.on('click', function () {
        // alert("reqmattab");
    });

    //查询已完成生产任务
    achievetask.on('click', function () {
        // alert("achievetab");
        // adaptTH();
    });

    //保存备料申请
    reqpickm.on('click', function () {
        //如果没有任务被选中，则操作无反应
        if(null == editReqpickm || editReqpickm.length==0){
            return ;
        }

        var reqBody = $("#req").find("tbody");
        var reqNums = reqBody.find("input.nnum");
        var reqTimes = reqBody.find("input.reqtimevalue");
        //校验需求重量值规范
        for(var x =0;x<reqNums.length;x++   ){
            if(isNaN(parseFloat(reqNums[x].value)) || reqNums[x].value<=0){
                alert("需求重量必须非空且大于0！")
                return;
            }
        }

        //校验送达时限值规范
        for(var x =0;x<reqTimes.length;x++){
            var timeFrag = reqTimes[x].value.split(":");
            if(0>timeFrag[0] || timeFrag[0]>23 || 0>timeFrag[1] ||
                timeFrag[1]>59 || !isInteger(timeFrag[0]) || !isInteger(timeFrag[1])){
                alert("送达时限不合规范")
                return;
            }
        }

        //保存备料申请到后台
        saveReqPickm(editReqpickm);

    });



});

//根据回传数据构造列表
function constructTask(tasks) {
    var list = tasks.tasks;
    if(null == list || list.length ==0){
        return;
    }
    var tbody = $("#task").find("tbody").empty();
    var result = "";
    for (var x in list) {
        if (x % 2 == 0) {
            result += "<tr class='success'";
        } else {
            result += "<tr";
        }
        result +=" onclick='rowClick(this)'>";
        result += "<td class='task_checkbox'><input type='checkbox' disabled='disabled' value=''>"
            + "<div class='billid' style='display: none'>" + list[x].billid + "</div>"
            + "<div class='matcode' style='display: none'>" + list[x].matcode + "</div>"
            + "</td>"
            + "<td class='machine'>" + list[x].workmachine + "</td>"
            + "<td class='matname'>" + list[x].matname + "</td>"
            + "<td class='matspec'>" + list[x].matspec + "</td>"
            + "<td class='mattype'>" + list[x].mattype + "</td>"
            + "<td class='matbatch'>" + list[x].matbatch + "</td>"
            + "<td class='reqnum'><div class='nnum'>" + list[x].reqNum + "</div><div class='unit'>"+ list[x].matunit+"</div></td>"
            + "<td class='starttime'>" + list[x].starttime + "</td>"
            + "<td class='status'>" + "未开始" + "</td>";
        result += "</tr>";

    }
    tbody.append(result);
    adaptTH();
}


//备料申请后台保存成功
function reqPickmSaved(msg) {
    if(msg == "error"){
        alert("后台服务出错，请稍后重试！");
        return;
    }

    //修改生成任务列表选中行状态
    var taskBody=$("#task").find("tbody");
    var trow = taskBody.find("tr");
    var taskStatus = taskBody.find("tr td.status");
    for(var x in selectedTask){
        //移除checkbox
        trow[selectedTask[x].rowNo].children[0].children[0].outerHTML="";
        //修改状态
        taskStatus[selectedTask[x].rowNo].innerText="要料中";
    }

    //修改备料申请状态
    var reqBody = $("#req").find("tbody");
    var checkboxes = reqBody.find(".task_checkbox");
    var reqNums = reqBody.find("input.nnum");
    var reqTimes = reqBody.find("input.reqtimevalue");
    var listLength = checkboxes.length-reqNums.length-1;
    //由编辑态转为显示态
    for(var x in editReqpickm){
        var rowNo = editReqpickm[x].editRowNo;
        for(var i in msg){
            if(rowNo == msg[i].editRowNo){
                checkboxes[rowNo].children[0].innerText = msg[i].billid;
                checkboxes[rowNo].children[1].innerText = msg[i].rowNo;
            }
        }
        checkboxes[rowNo].innerHTML +="<input type='checkbox' disabled='disabled' value=''>";
        reqNums[rowNo-listLength].outerHTML ="<div class='nnum'>" + reqNums[rowNo-listLength].value+ "</div>";
        reqTimes[rowNo-listLength].outerHTML = reqTimes[rowNo-listLength].value;
        changeStatus(rowNo,"要料中");
        if(rowNo%2==1){
            reqBody.find("tr")[rowNo].className = "success";
        }else{
            reqBody.find("tr")[rowNo].className = "";
        }
    }
    //清空编辑态备料申请
    editReqpickm.splice(0,editReqpickm.length);

    //清空选中任务
    selectedTask.splice(0,selectedTask.length);

    adaptTH();
}

//备料申请操作失败
function reqPickmFailed() {
    alert("无法连接到服务器，请稍后重试！");
}

//变更备料申请状态
function changeStatus(row, statusText) {
    var status =  $("#req").find("tbody").find(".status");
    status[row].innerHTML=statusText;
}


//任务列表行点击处理
function rowClick(tableRow) {
    var col =tableRow.childNodes;
    var checkbox = col[0];
    if(checkbox.children.length <=2){
        return;
    }
    //如果checkbox未被选中，则选中，加入到被选中任务数组
    if(!checkbox.firstChild.checked){
        checkbox.firstChild.checked = true;
        var matCode = checkbox.lastChild.innerText;
        var matBatch=tableRow.childNodes[5].innerText;
        var reqNum = tableRow.childNodes[6].childNodes[0].innerText;
        var task= {
            rowNo:tableRow.rowIndex-1,
            matCode:matCode,
            matBatch:matBatch,
            reqNum:reqNum
        };
        selectedTask.push(task);

        var hasMat = false;
        var matRow = -1;

        //检查备料申请行，是否已有相同物料
        for(var x in editReqpickm){
            if(editReqpickm[x].matCode == matCode && editReqpickm[x].matBatch == matBatch){
                hasMat = true;
                matRow = editReqpickm[x].editRowNo;
                break;
            }
        }
        if(hasMat){
            //更新行需求重量
            updateReqNum(matRow,reqNum);
            for(var i in editReqpickm){
                if(editReqpickm[i].matCode == matCode && editReqpickm[x].matBatch == matBatch){
                    editReqpickm[i].reqNum = addReqNum(editReqpickm[i].reqNum,reqNum);
                }
            }
        }
        else {
            var reqPickm = constructReqPickm(tableRow);
            //如果没有，则添加到需求物料汇总editReqpickm
            //备料申请表汇总编辑

            var editRowNo = addReqPickm([reqPickm]);
            var reqEditRow = {
                editRowNo:editRowNo,
                matCode :matCode,
                matBatch:matBatch,
                reqNum:reqPickm.reqnum,
                reqTime:reqPickm.reqtime
            }
            editReqpickm.push(reqEditRow);
        }

    }
    //如果checkbox已被选中，则弃选，正在编辑的备料计划需求重量减去该行任务需求重量
    else{
        checkbox.firstChild.checked = false;
        //从被选中任务数组中删除
        var rowIndex = tableRow.rowIndex-1;
        var operateTask=null;
        for(var i=0;i<selectedTask.length;i++){
            if(selectedTask[i].rowNo ==  rowIndex){
                operateTask =selectedTask[i];
                selectedTask.splice(i,1);
                break;
            }
        }

        var index = -1;
        //备料申请减去相应需求重量，若重量<=0，删除该备料申请行
        for(var i=0;i<editReqpickm.length;i++){
            if(operateTask.matCode == editReqpickm[i].matCode && operateTask.matBatch ==editReqpickm[i].matBatch){
                if(editReqpickm[i].reqNum - operateTask.reqNum<=0){
                    index = editReqpickm[i].editRowNo;
                    deleteEditRow(index);
                    editReqpickm.splice(i,1);
                }else{
                    editReqpickm[i].reqNum -= operateTask.reqNum;
                    updateReqNum(editReqpickm[i].editRowNo,0-operateTask.reqNum);
                }
                break;
            }
        }
        if(index !=-1){
            for(var x in editReqpickm){
                if(editReqpickm[x].editRowNo >index){
                    editReqpickm[x].editRowNo -=1;
                }
            }
        }
    }
    adaptTH();
}

//删除备料计划编辑行
function deleteEditRow(row) {
    var tBody = $("#req").find("tbody");
    tBody[0].removeChild(tBody[0].children[row]);
}

//从备料计划选中行构造备料申请需要的数据
function constructReqPickm(tableRow) {
    var pickm = {
        billid:"",
        matcode:"",
        matname:"",
        matspec:"",
        mattype:"",
        matbatch:"",
        matunit:"",
        donenum:0,
        reqnum:"",
        reqtime:""
    };
        pickm.matcode=tableRow.childNodes[0].lastChild.innerText;
        pickm.matname=tableRow.childNodes[2].innerText;
        pickm.matspec=tableRow.childNodes[3].innerText;
        pickm.mattype=tableRow.childNodes[4].innerText;
        pickm.matbatch=tableRow.childNodes[5].innerText;
        pickm.reqnum=tableRow.childNodes[6].childNodes[0].innerText;
        pickm.matunit=tableRow.childNodes[6].childNodes[1].innerText;
        var time = tableRow.childNodes[7].innerText;
        time = getReqTime(time);
        pickm.reqtime=time;
        return pickm;
}

//从开工时间前推半个小时得到送达时限
function  getReqTime(startTime) {
    var hm = startTime.split(":");
    var myDate = new Date();
    myDate.setHours(hm[0]);
    myDate.setMinutes(hm[1]-30);
    var minutes = myDate.getMinutes();
    if(minutes<10){
        minutes = "0"+minutes;
    }
    return myDate.getHours()+":"+minutes;
}

//更新备料申请行需求重量
function  updateReqNum(row,updateNum) {
    var editRow = $("#req").find("tbody").children()[row];
    var reqNumTD = editRow.children[5];
    reqNumTD.children[0].value = ""+(addReqNum((reqNumTD.children[0].value) ,updateNum));
}

//申请重量累加
function  addReqNum(req,update) {
    return parseFloat(req)+parseFloat(update);
}


//备料申请新增行,编辑态
function addReqPickm(reqpickm) {
    var tBody = $("#req").find("tbody");
    var addRow = tBody[0].lastElementChild.outerHTML;
    tBody[0].removeChild(tBody[0].lastElementChild);
    var result ="";
    for(var x in reqpickm){
        result += "<tr class='warning'";
        result +=" onclick='reqRowClick(this)'>";
        result +="<td class='task_checkbox'>"
            +"<div class='billid' style='display: none'>" + reqpickm[x].billid + "</div>"
            +"<div class='reqRowNo' style='display: none'></div>"
            + "<div class='matcode' style='display: none'>" + reqpickm[x].matcode + "</div>"
            + "</td>"
            +"<td class='matname'>"+reqpickm[x].matname+"</td>"
            +"<td class='matspec'>"+reqpickm[x].matspec+"</td>"
            +"<td class='mattype'>"+reqpickm[x].mattype+"</td>"
            +"<td class='matbatch'>"+reqpickm[x].matbatch+"</td>"
            +"<td class='reqnum'><input class='nnum' type='number' value='"+reqpickm[x].reqnum
            + "'/><div class='unit'>"+reqpickm[x].matunit+"</div></td>"
            +"<td class='reqtime' ><input class='reqtimevalue' type='time' value='"+reqpickm[x].reqtime+"'/></td>"
            +"<td class='doneNum'>"+reqpickm[x].donenum+"<div class='unit'>"+reqpickm[x].matunit+"</div></td>"
            +"<td class='status'>"+"编辑"+"</td>"
            +"</tr>";
    }
    result +=addRow;
    tBody.append(result);
    return tBody[0].childElementCount-2;
}

//判断是否是整数
function isInteger(obj) {
    return Math.floor(obj) === parseFloat(obj);
}

//自定义数据，用于显示测试
var tasks = [];
